const {dialog, ipcMain} = require('electron');
let fs = require('fs');

ipcMain.handle('on-savejsonfile-event', async (e, args) => {
    let jsonData = JSON.parse(args)
    let fileName = "" + Date.now() + ".json";
    fs.readFile('./public/overview.json', function (err, data) {
        if (err) {
            return console.error(err);
        }
        let overviewData = null
        if (data.toString() !== "") {
            overviewData = eval("(" + data.toString('utf-8') + ")");
            for (let i = 0; i < overviewData.dbs.length; i++) {
                if (overviewData.dbs[i].name === jsonData.name && overviewData.dbs[i].database === jsonData.database) {
                    dialog.showMessageBox({
                        message: "系统中已存在相同试卷",
                        type: 'error',
                        title: '系统信息'
                    })
                    return console.error("系统中已存在相同试卷");
                }
            }
        } else {
            let str = "{\"dbs\": []}"
            overviewData = eval("(" + str + ")")
        }

        let overview = "{\"database\": \"" + jsonData.database + "\",\"name\": \"" + jsonData.name + "\",\"exam_date\": \"" + jsonData.exam_date + "\",\"duration\": " + jsonData.duration + ",\"question_volume\": " + jsonData.question_volume + ",\"file_name\": \"" + fileName + "\"}"
        overviewData.dbs.unshift(eval("(" + overview + ")"))
        fs.writeFile('./public/overview.json', JSON.stringify(overviewData), function (err) {
            if (err) {
                dialog.showMessageBox({
                    message: err,
                    type: 'error',
                    title: '系统信息'
                })
                return console.error(err);
            }
            fs.writeFile('./public/' + fileName, args, function (err) {
                if (err) {
                    dialog.showMessageBox({
                        message: err,
                        type: 'error',
                        title: '系统信息'
                    })
                    return console.error(err);
                }
                dialog.showMessageBox({
                    message: "保存成功",
                    type: 'info',
                    title: '系统信息'
                })
                return fileName
            });
        })
    })
})




